﻿using System;
using System.Web;
using Autofac;
using NHibernate;
using NHibernate.Context;

namespace DDDSample.UI.Mvc
{
    public class MyModule : IHttpModule
    {
        public void Init(HttpApplication context)
        {
            context.BeginRequest += OnContextBeginRequest;
            context.EndRequest += OnContextEndRequest;
        }

        private static void OnContextBeginRequest(object sender, EventArgs e)
        {
            var session = IocHelper.Container.Resolve<ISessionFactory>().OpenSession();
            CurrentSessionContext.Bind(session);
        }

        private static void OnContextEndRequest(object sender, EventArgs e)
        {
            var session = CurrentSessionContext.Unbind(IocHelper.Container.Resolve<ISessionFactory>());
            if (session != null)
            {
                session.Flush();
                session.Dispose();
            }
        }

        public void Dispose()
        {
        }
    }
}